/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.beans;

import com.smarttmt.idu.ejb.domain.Constants;
import com.smarttmt.idu.web.behavior.Preloadable;
import com.smarttmt.idu.web.model.Chip;
import com.smarttmt.idu.web.model.UserLogin;
import com.smarttmt.idu.web.persistence.controller.UscochipJpaController;
import com.smarttmt.idu.web.persistence.controller.UsuacontJpaController;
import com.smarttmt.idu.web.persistence.controller.VwEstadocuentaValorizaJpaController;
import com.smarttmt.idu.web.persistence.entity.Uscochip;
import com.smarttmt.idu.web.persistence.entity.UscochipPK;
import com.smarttmt.idu.web.persistence.entity.Usuacont;
import com.smarttmt.idu.web.utilities.FacesUtils;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "inmobRegistryValidatorBean")
@SessionScoped
public class InmobRegistryValidator extends SmartIduBackingBean implements Serializable, Preloadable {

    private VwEstadocuentaValorizaJpaController vwEstadocuentaValorizaJpaController;
    @PersistenceUnit(unitName = "smarttmtiduappPU")
    EntityManagerFactory emf;
    @Resource
    UserTransaction utx;
    private boolean authorized;
    private String inmobRegistryNumber;
    private String inmobAddressNumber;
    private String inmobRegistryNumberCHIP;
    private String inmobAddressNumberCHIP;
    private boolean showAddress = false;
    private java.util.List<SelectItem> inmobRegistryNumberSelectItemList;
    private java.util.List<SelectItem> inmobAddressNumberSelectItemList;
    private Chip chip;
    private UscochipJpaController uscochipJpaController;
    private UsuacontJpaController usuacontJpaController;

    /**
     * Creates a new instance of InmobRegistryValidator
     */
    public InmobRegistryValidator() {
        super();
    }

    @PostConstruct
    public void initPostConstructorInmobRegistryValidator() {
        vwEstadocuentaValorizaJpaController = new VwEstadocuentaValorizaJpaController(utx, emf);
        uscochipJpaController = new UscochipJpaController(utx, emf);
        usuacontJpaController = new UsuacontJpaController(utx, emf);
    }

    public void resetData() {
        this.authorized = false;
        this.inmobRegistryNumber = null;
        this.inmobAddressNumber = null;
        this.showAddress = false;
        this.chip = new Chip();
        this.inmobAddressNumberSelectItemList = null;
        this.inmobRegistryNumberSelectItemList = null;
        this.inmobAddressNumberCHIP = null;
        this.inmobRegistryNumberCHIP = null;
    }

    @Override
    public void preload(Map<String, Object> parameters) throws Exception {
        resetData();
        String chipNumber = (String) parameters.get("chipNumber");
        getChip().setChipNumber(chipNumber);
        buildMatriculaDireccion();
    }

    public void buildMatriculaDireccion() {
        String aux = vwEstadocuentaValorizaJpaController.MatriculaDireccion(getChip().getChipNumber());
        System.out.println(aux);

        String[] splitSTROrig = aux.split("@");
        System.out.println("Longitud: " + splitSTROrig.length);
        String[] splitSTR = splitSTROrig[0].split("\\|");
        inmobRegistryNumberCHIP = splitSTR[0];
        System.out.println(inmobRegistryNumberCHIP);
        inmobAddressNumberCHIP = splitSTR[1];
        System.out.println(inmobAddressNumberCHIP);

        java.util.Map<Integer, String> mapElementsA = new HashMap<>();
        Integer m;
        for (m = 1; m <= 3; m++) {
            mapElementsA.put(m, splitSTROrig[m].split("\\|")[0]);
        }
        
        java.util.Map<Integer, String> mapElementsB = new HashMap<>();
        Integer mu;
        for (mu = 1; mu <= 3; mu++) {
            mapElementsB.put(mu, splitSTROrig[mu].split("\\|")[1]);
        }

        if (inmobAddressNumberCHIP != null) {
            if (inmobAddressNumberSelectItemList == null) {
                inmobAddressNumberSelectItemList = new java.util.ArrayList<>();
            }

            Integer num = randInt(0, 3);
            Integer i;
            for (i = 0; i <= 3; i++) {
                if (i == num) {
                    inmobAddressNumberSelectItemList.add(new SelectItem(inmobAddressNumberCHIP, inmobAddressNumberCHIP, inmobAddressNumberCHIP));
                } else {
                    String valElem = null;
                    boolean indicator = true;
                    while(indicator){
                        valElem = null;
                        Integer numb = randInt(1, 3);
                        valElem = mapElementsB.get(numb);
                        if(valElem!=null){
                            mapElementsB.remove(numb);
                            indicator = false;
                        }
                    }
                    inmobAddressNumberSelectItemList.add(new SelectItem(valElem, valElem, valElem));
                }
            }
        }

        if (inmobRegistryNumberCHIP != null) {
            if (inmobRegistryNumberSelectItemList == null) {
                inmobRegistryNumberSelectItemList = new java.util.ArrayList<>();
            }
            Integer num = randInt(0, 3);
            Integer i;
            for (i = 0; i <= 3; i++) {
                if (i == num) {
                    inmobRegistryNumberSelectItemList.add(new SelectItem(inmobRegistryNumberCHIP, inmobRegistryNumberCHIP, inmobRegistryNumberCHIP));
                } else {
                    String valElem = null;
                    boolean indicator = true;
                    while(indicator){
                        valElem = null;
                        Integer numb = randInt(1, 3);
                        valElem = mapElementsA.get(numb);
                        if(valElem!=null){
                            mapElementsA.remove(numb);
                            indicator = false;
                        }
                    }
                    inmobRegistryNumberSelectItemList.add(new SelectItem(valElem, valElem, valElem));
                }
            }

        }

        /*
         String[] splitSTR = aux.split("\\|");
         System.out.println("Longitud: " + splitSTR.length);
         inmobRegistryNumberCHIP = splitSTR[0];
         System.out.println(inmobRegistryNumberCHIP);
         inmobAddressNumberCHIP = splitSTR[1];
         System.out.println(inmobAddressNumberCHIP);
        
         buildInmobRegistryNumberSelectItemList();
         buildInmobAddressSelectItemList();
         */
    }

    public void buildInmobAddressSelectItemList() {
        if (inmobAddressNumberCHIP != null) {
            if (inmobAddressNumberSelectItemList == null) {
                inmobAddressNumberSelectItemList = new java.util.ArrayList<>();
            }
            Integer num = randInt(0, 3);
            String auxnewnum = "";
            Integer i;
            for (i = 0; i <= 3; i++) {
                if (i == num) {
                    inmobAddressNumberSelectItemList.add(new SelectItem(inmobAddressNumberCHIP, inmobAddressNumberCHIP, inmobAddressNumberCHIP));
                } else {
                    boolean indicator = true;
                    while (indicator) {
                        auxnewnum = transformNumber(inmobAddressNumberCHIP);
                        indicator = (auxnewnum.equals(inmobAddressNumberCHIP));
                    }

                    inmobAddressNumberSelectItemList.add(new SelectItem(auxnewnum, auxnewnum, auxnewnum));
                }
            }
        }
    }

    public void buildInmobRegistryNumberSelectItemList() {
        if (inmobRegistryNumberCHIP != null) {
            if (inmobRegistryNumberSelectItemList == null) {
                inmobRegistryNumberSelectItemList = new java.util.ArrayList<>();
            }
            Integer num = randInt(0, 3);
            String auxnewnum = "";
            Integer i;
            for (i = 0; i <= 3; i++) {
                if (i == num) {
                    inmobRegistryNumberSelectItemList.add(new SelectItem(inmobRegistryNumberCHIP, inmobRegistryNumberCHIP, inmobRegistryNumberCHIP));
                } else {
                    boolean indicator = true;
                    while (indicator) {
                        auxnewnum = transformNumber(inmobRegistryNumberCHIP);
                        indicator = (auxnewnum.equals(inmobRegistryNumberCHIP));
                    }

                    inmobRegistryNumberSelectItemList.add(new SelectItem(auxnewnum, auxnewnum, auxnewnum));
                }
            }

        }
    }

    public String transformNumber(String oldnum) {
        Integer a = randInt(0, 9);
        Integer b = randInt(0, 9);
        return oldnum.replace(a.toString(), b.toString());
    }

    public static int randInt(int min, int max) {

        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }

    public boolean validateInmobRegistryAnswer() {
        return inmobRegistryNumberCHIP.equals(inmobRegistryNumber);
    }

    public String validateInmobRegistry() {
        if (validateInmobRegistryAnswer()) {
            setShowAddress(true);
            try {
                this.chip.setInmobRegistryNumber(inmobRegistryNumber);
            } catch (Exception e) {
            }
            return null;
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Numero de matricula inmobiliaria erroneo", "El sistema ha interrumpido el proceso..."));
            return "userLogin";
        }
    }

    public boolean validateInmobAddressAnswer() {
        return inmobAddressNumberCHIP.equals(inmobAddressNumber);
    }

    public String validateInmobAddress() {
        if (validateInmobAddressAnswer()) {
            saveCHIPtoUser();
            setAuthorized(true);
            try {
                this.chip.setInmobAddressNumber(inmobAddressNumber);
                //rutina para adicionar el parametro inmobRegistryNumber validado
                Preloadable bean = (Preloadable) FacesUtils.getManagedBean("customerOperationsBean");
                java.util.Map<String, Object> parameters = new HashMap<>();
                parameters.put("chip", chip);
                bean.preload(parameters);
            } catch (Exception e) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ocurrio un error mientras procesabamos su solicitud", "El sistema ha interrumpido el proceso..."));
                return null;
            }
            if (isAuthorized()) {
                return "customerOperations";
            } else {
                return null;
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Direccion de predio erronea", "El sistema ha interrumpido el proceso..."));
            return "userLogin";
        }

    }

    public void saveCHIPtoUser() {
        try {
            UserLogin userLogin;
            if (getUserLoginBean().getUsername() != null) {
                userLogin = getUserLoginBean();
            } else {
                userLogin = (UserLogin) FacesUtils.getManagedBean("userLoginBean");
            }
            System.out.println("********************Usuario a consultar: " + userLogin.getUsername());
            Usuacont usuacont = usuacontJpaController.getUserByUsconomb(userLogin.getUsername());
            System.out.println("ID del usuario: " + usuacont.getUscocodi());
            System.out.println("******NUMERO DE CHIP: " + chip.getChipNumber());
            Uscochip uscochip = new Uscochip();
            uscochip.setUsuacont(usuacont);
            uscochip.setUcchesta(Constants.USER_ACTIVE);
            uscochip.setUscochipPK(new UscochipPK(chip.getChipNumber(), new BigInteger(usuacont.getUscocodi().toString())));
            System.out.println("LLamado a guardar");
            uscochipJpaController.create(uscochip);
        } catch (Exception e) {
            e.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "No fué posible guardar la validacion de CHIP", "Validarlo de nuevo"));
        }
    }

    public boolean isAuthorized() {
        return authorized;
    }

    public void setAuthorized(boolean authorized) {
        this.authorized = authorized;
    }

    public String getInmobRegistryNumber() {
        return inmobRegistryNumber;
    }

    public void setInmobRegistryNumber(String inmobRegistryNumber) {
        this.inmobRegistryNumber = inmobRegistryNumber;
    }

    public String getInmobAddressNumber() {
        return inmobAddressNumber;
    }

    public void setInmobAddressNumber(String inmobAddressNumber) {
        this.inmobAddressNumber = inmobAddressNumber;
    }

    public boolean isShowAddress() {
        return showAddress;
    }

    public void setShowAddress(boolean showAddress) {
        this.showAddress = showAddress;
    }

    public Chip getChip() {
        return chip;
    }

    public void setChip(Chip chip) {
        this.chip = chip;
    }

    public VwEstadocuentaValorizaJpaController getVwEstadocuentaValorizaJpaController() {
        return vwEstadocuentaValorizaJpaController;
    }

    public void setVwEstadocuentaValorizaJpaController(VwEstadocuentaValorizaJpaController vwEstadocuentaValorizaJpaController) {
        this.vwEstadocuentaValorizaJpaController = vwEstadocuentaValorizaJpaController;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public UserTransaction getUtx() {
        return utx;
    }

    public void setUtx(UserTransaction utx) {
        this.utx = utx;
    }

    public String getInmobRegistryNumberCHIP() {
        return inmobRegistryNumberCHIP;
    }

    public void setInmobRegistryNumberCHIP(String inmobRegistryNumberCHIP) {
        this.inmobRegistryNumberCHIP = inmobRegistryNumberCHIP;
    }

    public String getInmobAddressNumberCHIP() {
        return inmobAddressNumberCHIP;
    }

    public void setInmobAddressNumberCHIP(String inmobAddressNumberCHIP) {
        this.inmobAddressNumberCHIP = inmobAddressNumberCHIP;
    }

    public List<SelectItem> getInmobRegistryNumberSelectItemList() {
        return inmobRegistryNumberSelectItemList;
    }

    public void setInmobRegistryNumberSelectItemList(List<SelectItem> inmobRegistryNumberSelectItemList) {
        this.inmobRegistryNumberSelectItemList = inmobRegistryNumberSelectItemList;
    }

    public List<SelectItem> getInmobAddressNumberSelectItemList() {
        return inmobAddressNumberSelectItemList;
    }

    public void setInmobAddressNumberSelectItemList(List<SelectItem> inmobAddressNumberSelectItemList) {
        this.inmobAddressNumberSelectItemList = inmobAddressNumberSelectItemList;
    }

    public UscochipJpaController getUscochipJpaController() {
        return uscochipJpaController;
    }

    public void setUscochipJpaController(UscochipJpaController uscochipJpaController) {
        this.uscochipJpaController = uscochipJpaController;
    }

    public UsuacontJpaController getUsuacontJpaController() {
        return usuacontJpaController;
    }

    public void setUsuacontJpaController(UsuacontJpaController usuacontJpaController) {
        this.usuacontJpaController = usuacontJpaController;
    }

}
